#!/bin/bash

userName=`whoami` ##用户名
packPath=/Users/${userName}/workspace/workCodes/socket/Applications/AutoPack
downPath=/Users/${userName}/workspace/workCodes/upload/package
packName=$1
packConfig=$2
bundleId=$5
cerkey=$3
cerkmd5=$6
channel=$7
itermid=$4
timedown=`date '+%Y%m%d%H%M%S'`
cerkPath=/Users/${userName}/Library/Keychains/login.keychain

tempFile=temp.entitlements

unzip -q -o $packPath/ipa/$packName -d $packPath
chmod -R 777 $packPath/Payload
chmod 777 $packPath/$tempFile 
##获取解压后的文件夹
dir=$(ls $packPath/Payload)

for unpath in $dir
do
     pakpth=$unpath
done 

##拷贝授权文件
cp $packPath/mobileprovision/$packConfig $packPath/Payload/$pakpth/embedded.mobileprovision
##设置info.plist文件
/usr/libexec/plistbuddy -c 'Set :CFBundleIdentifier '"\"${bundleId}"\"'' $packPath/Payload/${pakpth}/Info.plist
/usr/libexec/plistbuddy -c 'Set :CerBundleID '"\"${cerkmd5}"\"'|'"\"${channel}"\"'' $packPath/Payload/${pakpth}/Info.plist
if [ $? -eq 0 ];then 
	echo 'Set True' 
	else 
	echo 'Set false change to Add'
/usr/libexec/plistbuddy -c 'Add :CerBundleID String '"\"${cerkmd5}"\"'|'"\"${channel}"\"'' $packPath/Payload/${pakpth}/Info.plist
fi
/usr/libexec/plistbuddy -c 'Set :application-identifier '"\"${itermid}"\"'.'"\"${bundleId}"\"'' ${packPath}/${tempFile}
/usr/libexec/plistbuddy -c 'Set :com.apple.developer.team-identifier '"\"${itermid}"\"'' ${packPath}/${tempFile}
/usr/libexec/plistbuddy -c 'Set :keychain-access-groups:0 '"\"${itermid}"\"''.* ${packPath}/${tempFile}

##解锁证书
security unlock-keychain "-p" "jufeng123" $cerkPath

/usr/bin/codesign --preserve-metadata=identifier,entitlements -f -s "$cerkey" --identifier "$bundleId" --entitlements $packPath/$tempFile $packPath/Payload/$unpath/
cd $packPath
zip -r -q $packPath/temp.ipa Payload/

filename=$(basename "$packName")
filename="${filename%.*}"
mv $packPath/temp.ipa $downPath/$filename.$channel.ipa
#echo $filename.$channel.$timedown.ipa > $downPath/filename
rm -rf $packPath/Payload
rm -rf 

	